/*
 * @Author: cygao
 * @Date: 2018-11-19 21:58:25
 * @Last Modified by: caijw
 * @Last Modified time: 2019-01-10 23:06:17
 */

import React, { Component } from 'react';
import { connect } from "react-redux";
import * as actions from '../../../store/action/community';
import '../../../static/css/weui.less';
import { CityPicker,Toast,Toptips  } from 'react-weui';
import cnCity from '../../my/personal/address/cnCity';
import axios from '../../../api/api';
import './edit.less';
import Utils from '../../../utils';

class Edit extends Component{
  state = {
    tab: 0,
    url: '',
    city_show: false,
    city_value: '',
    province_code : '',
    city_code : '',
    district_code : '',
    fetching : false,
    content : '',
    img : [],
    intention: '',
    username : '',
    phone: '',
    showTipToast : {
      show : false,
    }
  }
  
  constructor () {
    super();
    this.onChooseImage = this.onChooseImage.bind(this);
  }


   //退出登陆
   logout = () =>{
        localStorage.setItem('token', '');
        //判断是否登陆
        this.isLogin();
    }
    //判断是否登陆
    isLogin = () => {
        if(!localStorage.getItem('token')){
            this.props.history.push('/glogin')
        }
    }
  back = () =>{
    this.props.history.go(-1);
  }
  changeTab(tab){
      this.setState({
          tab: tab
      })
  }
  componentWillMount(){
     //判断是否登陆
    this.isLogin();
    // console.log(this.props.submitTopic);
    // console.log(this.props.uploadImg)
  }
  uploadPic(e){
      var self = this;
      self.file = e.target.files[0];
      this.setState({
          fetching: true
      })
      axios.get(
          'api/oss-upload-token'
      ).then(function (response) {
          if (response.ret != 0) {
              alert(response.msg);
              return;
          }
          let client = new OSS({
              region: response.data.region,
          //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用STS方式来进行API访问
              accessKeyId: response.data.AccessKeyId,
              accessKeySecret: response.data.AccessKeySecret,
              stsToken: response.data.SecurityToken,
              bucket: response.data.bucket
          });
          client.put((new Date()).getTime() + self.file.name, self.file).then(function (r1) {
            var imgArr =  self.state.img;
            imgArr.push(r1.url);
            self.setState({
              img : imgArr
            })
          }).then(function (r2) {
              //console.log('get success: %j', r2);
              self.setState({
                fetching: false
              })
          }).catch(function (err) {
              //console.error('error: %j', err);
              self.setState({
                  fetching: false
              })
          });
      })
      .catch(function (error) {
          console.log(error);
      });
  }
  
  async onChooseImage() {
    try {
      const res = await Utils.pickImageFiles();
      console.log(JSON.stringify(res) + ";" + res.files + ";length" + res.files.length);
      if (!res || !res.files || res["files"].length == 0) {
        return;
      }
      // plus 未准备好
      if (!window["plus"]) return;

      this.setState({
        fetching: true
      });
      
      let ossToken = await axios.get('api/oss-upload-token');

      let client = new OSS({
        region: ossToken.data.region,
        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用STS方式来进行API访问
        accessKeyId: ossToken.data.AccessKeyId,
        accessKeySecret: ossToken.data.AccessKeySecret,
        stsToken: ossToken.data.SecurityToken,
        bucket: ossToken.data.bucket
      });

      for (let file of res.files) {
        /// ref: http://ask.dcloud.net.cn/article/412
        console.log("upload file:" + file);
        let entry = await Utils.resolveLocalFileSystemURL(file);
        let nativeFile = await Utils.getFileFromeEntry(entry);
        let evt = await Utils.readFileAsDataURL(entry);
        let format = nativeFile.type;
        //抽取DataURL中的数据部分，从Base64格式转换为二进制格式
        let bin = atob(evt.target.result.split(',')[1]);
        //创建空的Uint8Array
        let buffer = new Uint8Array(bin.length);
        //将图像数据逐字节放入Uint8Array中
        for (let i = 0; i < bin.length; i++) {
            buffer[i] = bin.charCodeAt(i);
        };
        //利用Uint8Array创建Blob对象
        let blob = new Blob([buffer.buffer], {type : format});
        
        let keyname = Date.now() + nativeFile.name;
        let clientRes = await client.put(keyname, blob);
        
        let imgArr =  this.state.img;
        imgArr.push(clientRes.url);
        this.setState({
          img : imgArr
        });

        console.log("upload res:" + JSON.stringify(clientRes));
      }
      this.setState({
        fetching: false
      });
      console.log("upload finished");
    } catch (e) {
      this.setState({
        fetching: false
      });
      console.log("upload error" + JSON.stringify(e));
    }
  }

  //提交帖子
  submitTopic(){
    var params = {};
    var img = [];
    img.push(this.state.url)
    if(this.state.tab === 0){
      params = {
        type: 2,
        content: this.state.content,
        images: this.state.img
      }
    }else{
      params = {
        type: 3,
        content: '123',
        apply_job: {
          intention: this.state.intention,
          province_code: this.state.province_code,
          city_code:  this.state.city_code,
          district_code: this.state.district_code,
          phone: this.state.phone,
          username : this.state.username
        }
      }
    }
    this.props.submitTopic(params);
  }

  //选择对应城市
  changeSelectCity = (text) =>{
        this.setState({city_value: text, city_show: false});
        let province = text.split(' ')[0];
        let city = text.split(' ')[1]
        let district = text.split(' ')[2];

        let cityArr = [];
        cnCity.forEach((item)=>{
            if(item.name == province){
                cityArr = item.sub;
                this.setState({province_code: item.code});
            }
        })
        let districtArr = [];
        cityArr.forEach((item)=>{
            if(item.name == city){
                districtArr = item.sub;
                this.setState({city_code: item.code});
            }
        })
        districtArr.forEach((item)=>{
            if(item.name == district){
                this.setState({district_code: item.code});
            }
        })
    }



     //这里可以设置
     componentWillReceiveProps = () =>{
        setTimeout(()=>{
            if(this.props.community.postTopRet == 0){
               this.props.history.go(-1);
            }else if(this.props.community.postTopRet == -1){
                this.setState({showTipToast: {show: true}});
                this.state.toastTimer = setTimeout(()=> {
                    this.setState({showTipToast: {show: false}});
                }, 2000);
            }
        },100)
    }
  render () {
    return (
      <div className="edit-container">
        <Toast icon="loading" show={this.state.fetching}>Loading...</Toast>
        {/* <Toptips type="info" show={this.state.showTipToast.show}>{this.props.community.postTopMsg}</Toptips> */}
        <div className="header">
          <i className="btn-back" onClick={this.back}></i>
          <p className="title">信息发布</p>
          <button className="commit" onClick={this.submitTopic.bind(this)}>发布</button>
        </div>
        <ul className="tab clearfix">
          <li><span className={ this.state.tab === 0 ? 'active': ''} onClick={this.changeTab.bind(this, 0)}>趣事发布</span></li>
          <li><span className={ this.state.tab === 1 ? 'active': ''} onClick={this.changeTab.bind(this, 1)}>简历发布</span></li>
        </ul>
        { this.state.tab === 0 ? (
           <div className="editor-container">
            <div className="fun-editor">
              <textarea placeholder="请在此处输入您想发布的趣事~" value={this.state.content} onChange={e=>{
                  var value = e.target.value.substring(0,300)
                  this.setState({content:value})}
              }></textarea>
              <div className="images-box">
                <div className="uploader-box" onClick={this.onChooseImage}>
                {/* <div className="uploader-box"> */}
                  <form ref={el => (this.form = el)}>
                    {/* <input className="uploader" type="file" name="image" accept="image/*" onChange={this.uploadPic.bind(this)} /> */}
                    <div className="uploader" />
                  </form>
                </div>
                {this.state.img.map((item)=>{
                     return <img src={item}/>
                })}
               
              </div>
              <div className="counter">{this.state.content.length}/300</div>
            </div>
          </div>
        ) : (
          <div className="resume-editor-container">
          <ul>
            <li>
              <span className="label">姓&emsp;&emsp;名</span>
              <input type="text" placeholder="请输入您的姓名"  value={this.state.username} onChange={e=>this.setState({username:e.target.value})}/>
            </li>
            <li>
              <span className="label">意向职位</span>
              <input type="text" placeholder="请输入您的意向职位"  value={this.state.intention} onChange={e=>this.setState({intention:e.target.value})} />
            </li>
            <li include="form-input-select()" className="select-container">
              <span className="label">地&emsp;&emsp;区</span>
              <input type="text"
                                value={this.state.city_value}
                                onClick={ e=> {
                                    e.preventDefault();
                                    this.setState({city_show: true})
                                }}
                                placeholder="请选择地址"
                                readOnly={true}
                            />
             
            </li>
            <li>
              <span className="label">手机号码</span>
              <input type="tel" placeholder="请输入您的手机号码"  value={this.state.phone} onChange={e=>this.setState({phone:e.target.value})}/>
            </li>
          </ul>
        </div>
        )}
        <CityPicker
            data={cnCity}
            onCancel={e=>this.setState({city_show: false})}
            onChange={this.changeSelectCity}
            show={this.state.city_show}
        />
      </div>
    )
  }
}

export default connect((state)=>{return {...state}}, actions)(Edit);